<?php
session_start();

if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}

require_once 'track_online.php';

// 定义 ensureFile 函数：检查并初始化文件
function ensureFile($filename, $defaultContent = '[]') {
    if (!file_exists($filename)) {
        file_put_contents($filename, $defaultContent);
    }
    $content = file_get_contents($filename);
    $data = json_decode($content, true);
    return is_array($data) ? $data : json_decode($defaultContent, true);
}

// 当前用户
$currentUser = $_SESSION['username'];

// 动态存储文件
$dtFile = __DIR__ . "/dt.json";
$dynamicList = ensureFile($dtFile);

// 点赞记录文件
$likeFile = __DIR__ . "/likes.json";
$likeRecords = ensureFile($likeFile);

// 评论存储文件 - 确保自动创建
$commentsFile = __DIR__ . "/comments.json";
$allComments = ensureFile($commentsFile, '{}');

// 用户称号文件
$titlesFile = __DIR__ . '/ch.json';
$allTitles = ensureFile($titlesFile, '{}');

// 获取用户头像
function getUserAvatar($username) {
    $userDir = __DIR__ . "/user/$username";
    if (!is_dir($userDir)) return null;
    
    $avatarFiles = ['avatar.png', 'avatar.jpg', 'avatar.jpeg', 'avatar.gif'];
    foreach ($avatarFiles as $file) {
        $path = "$userDir/$file";
        if (file_exists($path)) return "user/$username/$file";
    }
    return null;
}

// 获取用户称号
function getUserTitles($username) {
    global $allTitles;
    return $allTitles[$username] ?? [];
}

// 处理 POST 请求
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    // 发布动态
    if ($_POST['action'] === 'post_dynamic') {
        $title = trim($_POST['title']);
        $content = trim($_POST['content']);
        $allowComment = isset($_POST['allow_comment']) && $_POST['allow_comment'] === 'on';
        $allowLike = isset($_POST['allow_like']) && $_POST['allow_like'] === 'on';

        if (mb_strlen($title) > 150 || mb_strlen($content) > 500) {
            echo json_encode(['status' => 'error', 'message' => '标题或内容超出限制']);
            exit();
        }

        $dynamicList[] = [
            'id' => uniqid($currentUser, true),
            'user' => $currentUser,
            'date' => date('Y-m-d H:i:s'),
            'title' => htmlspecialchars($title),
            'content' => htmlspecialchars($content),
            'likes' => 0,
            'allow_comment' => $allowComment,
            'allow_like' => $allowLike
        ];

        file_put_contents($dtFile, json_encode($dynamicList));
        echo json_encode(['status' => 'success', 'message' => '动态发布成功']);
        exit();
    }

    // 点赞动态
    if ($_POST['action'] === 'like_dynamic') {
        $dynamicId = $_POST['id'];
        $index = null;

        foreach ($dynamicList as $i => $dynamic) {
            if ($dynamic['id'] === $dynamicId) {
                $index = $i;
                break;
            }
        }

        if ($index === null) {
            echo json_encode(['status' => 'error', 'message' => '动态不存在']);
            exit();
        }
        
        // 检查是否允许点赞
        if (!$dynamicList[$index]['allow_like']) {
            echo json_encode(['status' => 'error', 'message' => '该动态已禁用点赞']);
            exit();
        }
        
        // 检查是否为自己的动态
        if ($dynamicList[$index]['user'] === $currentUser) {
            echo json_encode(['status' => 'error', 'message' => '不能给自己的动态点赞']);
            exit();
        }

        // 初始化点赞记录
        if (!isset($likeRecords[$dynamicId])) $likeRecords[$dynamicId] = [];

        // 点赞逻辑
        if (in_array($currentUser, $likeRecords[$dynamicId])) {
            // 取消点赞
            $likeRecords[$dynamicId] = array_diff($likeRecords[$dynamicId], [$currentUser]);
            $dynamicList[$index]['likes']--;
        } else {
            // 点赞
            $likeRecords[$dynamicId][] = $currentUser;
            $dynamicList[$index]['likes']++;
        }

        // 保存文件
        file_put_contents($likeFile, json_encode($likeRecords));
        file_put_contents($dtFile, json_encode($dynamicList));
        echo json_encode(['status' => 'success', 'likes' => $dynamicList[$index]['likes'], 'id' => $dynamicId]);
        exit();
    }

    // 删除动态
    if ($_POST['action'] === 'delete_dynamic') {
        $dynamicId = $_POST['id'];
        $index = null;

        foreach ($dynamicList as $i => $dynamic) {
            if ($dynamic['id'] === $dynamicId) {
                $index = $i;
                break;
            }
        }

        if ($index === null) {
            echo json_encode(['status' => 'error', 'message' => '动态不存在']);
            exit();
        }

        // 确保当前用户是动态的发布者
        if ($dynamicList[$index]['user'] !== $currentUser) {
            echo json_encode(['status' => 'error', 'message' => '无权限删除动态']);
            exit();
        }

        unset($dynamicList[$index]);
        unset($likeRecords[$dynamicId]);
        if (isset($allComments[$dynamicId])) unset($allComments[$dynamicId]);

        $dynamicList = array_values($dynamicList);
        file_put_contents($dtFile, json_encode($dynamicList));
        file_put_contents($likeFile, json_encode($likeRecords));
        file_put_contents($commentsFile, json_encode($allComments));
        echo json_encode(['status' => 'success', 'message' => '动态删除成功']);
        exit();
    }
    
    // 添加评论
    if ($_POST['action'] === 'add_comment') {
        $dynamicId = $_POST['id'];
        $commentText = trim($_POST['comment']);
        $replyTo = $_POST['reply_to'] ?? null;
        
        if (mb_strlen($commentText) > 300) {
            echo json_encode(['status' => 'error', 'message' => '评论长度不能超过300字']);
            exit();
        }
        
        $index = null;
        foreach ($dynamicList as $i => $dynamic) {
            if ($dynamic['id'] === $dynamicId) {
                $index = $i;
                break;
            }
        }
        
        if ($index === null) {
            echo json_encode(['status' => 'error', 'message' => '动态不存在']);
            exit();
        }
        
        // 检查是否允许评论
        if (!$dynamicList[$index]['allow_comment']) {
            echo json_encode(['status' => 'error', 'message' => '该动态已禁用评论']);
            exit();
        }
        
        // 初始化评论
        if (!isset($allComments[$dynamicId])) $allComments[$dynamicId] = [];
        
        // 添加新评论
        $newComment = [
            'id' => uniqid($currentUser),
            'user' => $currentUser,
            'comment' => htmlspecialchars($commentText),
            'date' => date('Y-m-d H:i:s'),
            'reply_to' => $replyTo
        ];
        
        $allComments[$dynamicId][] = $newComment;
        
        file_put_contents($commentsFile, json_encode($allComments));
        echo json_encode([
            'status' => 'success',
            'message' => '评论添加成功',
            'comment' => $newComment,
            'id' => $dynamicId
        ]);
        exit();
    }
}

// 处理获取评论的请求
if (isset($_GET['get_comments']) && isset($_GET['id'])) {
    $dynamicId = $_GET['id'];
    $comments = $allComments[$dynamicId] ?? [];
    
    // 为每条评论添加回复的用户名（如果存在）
    foreach ($comments as &$comment) {
        if ($comment['reply_to']) {
            foreach ($comments as $c) {
                if ($c['id'] === $comment['reply_to']) {
                    $comment['reply_to_user'] = $c['user'];
                    break;
                }
            }
        }
    }
    
    header('Content-Type: application/json');
    echo json_encode($comments);
    exit();
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户动态 - JIILCHAT</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
        }
        
        body {
            background-color: #f5f7fa;
            color: #333;
        }
        
        .navbar {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            background: white;
            padding: 12px 20px;
            display: flex;
            align-items: center;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            z-index: 100;
        }
        
        .back-btn {
            background: none;
            border: none;
            color: #000;
            font-size: 18px;
            margin-right: 10px;
            cursor: pointer;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .navbar-title {
            font-size: 17px;
            font-weight: 600;
            flex-grow: 1;
        }
        
        .avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            object-fit: cover;
        }
        
        .dynamic-list {
            margin-top: 60px;
            padding: 15px;
            max-height: calc(100vh - 60px);
            overflow-y: auto;
        }
        
        .dynamic-card {
            background: white;
            border-radius: 12px;
            padding: 15px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
            margin-bottom: 15px;
            border: 1px solid #eee;
        }
        
        .card-header {
            display: flex;
            align-items: center;
            margin-bottom: 12px;
        }
        
        .avatar-container {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            overflow: hidden;
            background: #e0e4e9;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
        }
        
        .user-info {
            flex-grow: 1;
            min-width: 0;
        }
        
        .user-header {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 8px;
        }
        
        .user-name {
            font-weight: 600;
            font-size: 15px;
            color: #333;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            max-width: 150px;
        }
        
        .user-name:hover {
            text-decoration: underline;
        }
        
        .title-tag {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 10px;
            font-size: 11px;
            font-weight: 500;
            color: white;
        }
        
        .post-time {
            font-size: 12px;
            color: #888;
            margin-top: 2px;
        }
        
        .dynamic-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 8px;
            color: #222;
        }
        
        .dynamic-content {
            font-size: 14px;
            color: #444;
            line-height: 1.5;
            margin-bottom: 12px;
        }
        
        .card-actions {
            display: flex;
            justify-content: space-between;
            border-top: 1px solid #eee;
            padding-top: 10px;
        }
        
        .action-btn {
            background: transparent;
            border: none;
            border-radius: 8px;
            padding: 5px 10px;
            font-size: 13px;
            color: #666;
            cursor: pointer;
            display: flex;
            align-items: center;
        }
        
        .action-btn:hover {
            background: #f8f9fa;
            color: #0056b3;
        }
        
        .action-btn i {
            margin-right: 5px;
            font-size: 14px;
        }
        
        .action-btn.active {
            color: #e74c3c;
        }
        
        .comment-count, .like-count {
            font-size: 13px;
            margin-left: 3px;
        }
        
        .comments-btn {
            display: block;
            font-size: 12px;
            color: #3498db;
            margin-top: 8px;
            cursor: pointer;
        }
        
        .popup {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 200;
            justify-content: center;
            align-items: center;
        }
        
        .popup.active {
            display: flex;
        }
        
        .popup-content {
            background: white;
            width: 90%;
            max-width: 500px;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
        }
        
        .popup-header {
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .popup-title {
            font-size: 18px;
            font-weight: 600;
        }
        
        .close-popup {
            background: none;
            border: none;
            font-size: 22px;
            color: #777;
            cursor: pointer;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-input {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 10px;
            font-size: 14px;
            margin-bottom: 5px;
        }
        
        .form-input:focus {
            border-color: #3498db;
            outline: none;
        }
        
        .char-count {
            text-align: right;
            font-size: 12px;
            color: #888;
        }
        
        .form-options {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
        }
        
        .option-item {
            display: flex;
            align-items: center;
            font-size: 14px;
        }
        
        .option-item input {
            margin-right: 5px;
        }
        
        .submit-btn {
            background: #3498db;
            color: white;
            border: none;
            border-radius: 10px;
            padding: 12px 0;
            width: 100%;
            font-size: 15px;
            font-weight: 500;
            cursor: pointer;
        }
        
        .comments-container {
            max-height: 50vh;
            overflow-y: auto;
            margin-bottom: 15px;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
        }
        
        .comment {
            margin-bottom: 15px;
            padding: 12px;
            border-radius: 10px;
            background: #f8f9fa;
            font-size: 13px;
        }
        
        .comment-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }
        
        .comment-user {
            font-weight: 600;
            color: #3498db;
        }
        
        .comment-user:hover {
            text-decoration: underline;
        }
        
        .comment-time {
            font-size: 11px;
            color: #888;
        }
        
        .comment-text {
            color: #333;
            line-height: 1.4;
        }
        
        .reply-indicator {
            font-size: 12px;
            color: #888;
            margin-top: 5px;
            font-style: italic;
        }
        
        .reply-btn {
            font-size: 12px;
            color: #3498db;
            margin-top: 5px;
            cursor: pointer;
            text-align: right;
        }
        
        .comment-form {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        
        .comment-textarea {
            flex-grow: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 8px;
            resize: none;
            font-size: 14px;
            min-height: 45px;
        }
        
        .comment-btn {
            background: #3498db;
            color: white;
            border: none;
            border-radius: 8px;
            padding: 0 15px;
            cursor: pointer;
        }
        
        .no-dynamics {
            text-align: center;
            padding: 40px 20px;
            color: #999;
        }
        
        .comment-avatar {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 10px;
        }
        
        .comment-header-info {
            display: flex;
            align-items: center;
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 - 移除了右上角头像 -->
    <div class="navbar">
        <button class="back-btn" onclick="history.back()">
            <i class="fas fa-arrow-left"></i>
        </button>
        <div class="navbar-title">用户动态</div>
    </div>
    
    <div class="dynamic-list">
        <?php 
        $reversedDynamicList = array_reverse($dynamicList);
        foreach ($reversedDynamicList as $dynamic): 
            $id = $dynamic['id'];
            $allowComment = $dynamic['allow_comment'] ?? true;
            $allowLike = $dynamic['allow_like'] ?? true;
            $comments = $allComments[$id] ?? [];
            $userAvatar = getUserAvatar($dynamic['user']);
            $userTitles = getUserTitles($dynamic['user']);
        ?>
        <div class="dynamic-card" data-id="<?= $id ?>">
            <div class="card-header">
                <?php if ($userAvatar): ?>
                    <img src="<?= $userAvatar ?>" alt="头像" class="avatar" onclick="viewUser('<?= $dynamic['user'] ?>')">
                <?php else: ?>
                    <div class="avatar-container" onclick="viewUser('<?= $dynamic['user'] ?>')">
                        <?= substr($dynamic['user'], 0, 1) ?>
                    </div>
                <?php endif; ?>
                
                <div class="user-info">
                    <div class="user-header">
                        <a href="userinfo.php?user=<?= urlencode($dynamic['user']) ?>" class="user-name">
                            <?= htmlspecialchars($dynamic['user']) ?>
                        </a>
                        <?php foreach ($userTitles as $title): ?>
                            <span class="title-tag" style="background:<?= $title['color'] ?>">
                                <?= htmlspecialchars($title['name']) ?>
                            </span>
                        <?php endforeach; ?>
                    </div>
                    <div class="post-time"><?= htmlspecialchars($dynamic['date']) ?></div>
                </div>
            </div>
            
            <h3 class="dynamic-title"><?= htmlspecialchars($dynamic['title']) ?></h3>
            <div class="dynamic-content"><?= htmlspecialchars($dynamic['content']) ?></div>
            
            <div class="card-actions">
                <?php if ($allowLike): ?>
                <button class="action-btn like-btn <?= 
                    (isset($likeRecords[$id]) && in_array($currentUser, $likeRecords[$id])) ? 'active' : '' 
                ?>" onclick="toggleLike('<?= $id ?>')">
                    <i class="fas fa-heart"></i> 
                    <span class="like-count"><?= $dynamic['likes'] ?></span>
                </button>
                <?php else: ?>
                <button class="action-btn" disabled>
                    <i class="fas fa-heart" style="color:#ccc"></i> 
                    <span class="like-count" style="color:#ccc"><?= $dynamic['likes'] ?></span>
                </button>
                <?php endif; ?>
                
                <?php if ($allowComment): ?>
                <button class="action-btn" onclick="openComments('<?= $id ?>')">
                    <i class="fas fa-comment"></i> 
                    <span class="comment-count"><?= count($comments) ?></span>
                </button>
                <?php else: ?>
                <button class="action-btn" disabled>
                    <i class="fas fa-comment" style="color:#ccc"></i> 
                    <span class="comment-count" style="color:#ccc"><?= count($comments) ?></span>
                </button>
                <?php endif; ?>
                
                <?php if ($dynamic['user'] === $currentUser): ?>
                    <button class="action-btn delete-btn" onclick="deleteDynamic('<?= $id ?>')">
                        <i class="fas fa-trash-alt"></i>
                    </button>
                <?php endif; ?>
            </div>
            
            <?php if (count($comments) > 0): ?>
                <div class="comments-btn" onclick="openComments('<?= $id ?>')">
                    查看评论 (<?= count($comments) ?>)
                </div>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>
        
        <?php if (empty($dynamicList)): ?>
            <div class="no-dynamics">
                <i class="fas fa-newspaper fa-2x" style="opacity:0.5; margin-bottom:15px;"></i>
                <h3>暂无动态</h3>
                <p>发布第一条动态吧！</p>
            </div>
        <?php endif; ?>
    </div>
    
    <!-- 发布动态按钮 -->
    <button class="add-btn" onclick="togglePopup(true)" 
            style="position:fixed;bottom:20px;right:20px;background:#333;color:white;width:50px;height:50px;border-radius:50%;display:flex;justify-content:center;align-items:center;font-size:22px;cursor:pointer;">
        <i class="fas fa-plus"></i>
    </button>
    
    <!-- 发布动态弹出层 -->
    <div class="popup" id="post-popup">
        <div class="popup-content">
            <div class="popup-header">
                <div class="popup-title">发布动态</div>
                <button class="close-popup" onclick="togglePopup(false)">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <form onsubmit="postDynamic(event)">
                <div class="form-group">
                    <input type="text" class="form-input" id="title" placeholder="标题 (最多150字)" maxlength="150" required>
                    <div class="char-count"><span id="title-count">0</span>/150</div>
                </div>
                
                <div class="form-group">
                    <textarea class="form-input" id="content" placeholder="内容 (最多500字)" maxlength="500" required 
                              style="min-height:100px; resize:vertical"></textarea>
                    <div class="char-count"><span id="content-count">0</span>/500</div>
                </div>
                
                <div class="form-options">
                    <div class="option-item">
                        <input type="checkbox" id="allow_comment" name="allow_comment" checked>
                        <label for="allow_comment">允许评论</label>
                    </div>
                    <div class="option-item">
                        <input type="checkbox" id="allow_like" name="allow_like" checked>
                        <label for="allow_like">允许点赞</label>
                    </div>
                </div>
                
                <button type="submit" class="submit-btn">发布</button>
            </form>
        </div>
    </div>
    
    <!-- 评论弹出层 -->
    <div class="popup" id="comments-popup">
        <div class="popup-content">
            <div class="popup-header">
                <div class="popup-title">评论</div>
                <button class="close-popup" onclick="closeComments()">
                    <i class="fas fa-times"></i>
                </button>
            </div>
            
            <div class="comments-container" id="comments-container">
                <!-- 评论内容将在这里加载 -->
            </div>
            
            <div class="comment-form">
                <textarea class="comment-textarea" id="comment-text" placeholder="写下你的评论..."></textarea>
                <button class="comment-btn" onclick="postComment()">
                    <i class="fas fa-paper-plane"></i>
                </button>
            </div>
            <div id="reply-info" style="display:none;font-size:12px;color:#888;margin-top:5px;"></div>
        </div>
    </div>
    
    <script>
        let currentDynamicId = null;
        let replyCommentId = null;
        
        // 更新字符计数
        document.getElementById('title')?.addEventListener('input', function() {
            document.getElementById('title-count').textContent = this.value.length;
        });
        
        document.getElementById('content')?.addEventListener('input', function() {
            document.getElementById('content-count').textContent = this.value.length;
        });
        
        // 发布动态弹出层
        function togglePopup(show) {
            const popup = document.getElementById('post-popup');
            popup.classList.toggle('active', show);
        }
        
        // 打开评论弹窗
        function openComments(dynamicId) {
            currentDynamicId = dynamicId;
            const popup = document.getElementById('comments-popup');
            popup.classList.add('active');
            loadComments(dynamicId);
        }
        
        // 关闭评论弹窗
        function closeComments() {
            const popup = document.getElementById('comments-popup');
            popup.classList.remove('active');
            document.getElementById('comment-text').value = '';
            document.getElementById('reply-info').style.display = 'none';
            document.getElementById('reply-info').textContent = '';
            replyCommentId = null;
        }
        
        // 加载评论
        function loadComments(dynamicId) {
            const container = document.getElementById('comments-container');
            container.innerHTML = '<div style="text-align:center;padding:30px"><i class="fas fa-spinner fa-spin"></i></div>';
            
            fetch(`dt.php?get_comments=1&id=${dynamicId}`)
                .then(response => response.json())
                .then(comments => {
                    if (comments.length === 0) {
                        container.innerHTML = '<div style="text-align:center;padding:20px;color:#888">还没有评论，留下第一条评论吧！</div>';
                        return;
                    }
                    
                    let html = '';
                    comments.forEach(comment => {
                        const isReply = comment.reply_to && comment.reply_to !== '';
                        let replyInfo = '';
                        
                        if (isReply && comment.reply_to_user) {
                            replyInfo = `<div class="reply-indicator">回复 @${comment.reply_to_user}</div>`;
                        }
                        
                        html += `
                        <div class="comment" data-id="${comment.id}">
                            <div class="comment-header">
                                <div class="comment-header-info">
                                    <span class="comment-user" onclick="viewUser('${comment.user}')">
                                        ${comment.user}
                                    </span>
                                </div>
                                <div class="comment-time">${comment.date}</div>
                            </div>
                            ${replyInfo}
                            <div class="comment-text">${comment.comment}</div>
                            <div class="reply-btn" onclick="setReply('${comment.id}', '${comment.user}')">回复</div>
                        </div>
                        `;
                    });
                    
                    container.innerHTML = html;
                    container.scrollTop = container.scrollHeight;
                })
                .catch(error => {
                    console.error('加载评论失败:', error);
                    container.innerHTML = '<div style="text-align:center;padding:20px;color:#f00">加载评论失败，请重试</div>';
                });
        }
        
        // 设置回复对象
        function setReply(commentId, username) {
            replyCommentId = commentId;
            const replyInfo = document.getElementById('reply-info');
            replyInfo.textContent = `回复 ${username}：`;
            replyInfo.style.display = 'block';
            document.getElementById('comment-text').focus();
        }
        
        // 发布评论
        function postComment() {
            const text = document.getElementById('comment-text').value.trim();
            if (!text) return;
            
            const formData = new FormData();
            formData.append('action', 'add_comment');
            formData.append('id', currentDynamicId);
            formData.append('comment', text);
            if (replyCommentId) {
                formData.append('reply_to', replyCommentId);
            }
            
            fetch('dt.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(result => {
                if (result.status === 'success') {
                    // 重新加载评论
                    loadComments(currentDynamicId);
                    // 清空输入框
                    document.getElementById('comment-text').value = '';
                    replyCommentId = null;
                    document.getElementById('reply-info').style.display = 'none';
                    
                    // 更新评论计数
                    const commentCountEl = document.querySelector(`[data-id="${currentDynamicId}"] .comment-count`);
                    commentCountEl.textContent = parseInt(commentCountEl.textContent || 0) + 1;
                } else {
                    alert('评论失败: ' + result.message);
                }
            })
            .catch(error => {
                console.error('发布评论失败:', error);
                alert('评论发布失败，请重试');
            });
        }
        
        // 点赞动态
        async function toggleLike(dynamicId) {
            const likeBtn = document.querySelector(`[data-id="${dynamicId}"] .like-btn`);
            const likeCountEl = document.querySelector(`[data-id="${dynamicId}"] .like-count`);
            
            const response = await fetch('dt.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ action: 'like_dynamic', id: dynamicId })
            });
            
            const result = await response.json();
            if (result.status === 'success') {
                likeCountEl.textContent = result.likes;
                likeBtn.classList.toggle('active');
            } else {
                alert(result.message);
            }
        }
        
        // 删除动态
        async function deleteDynamic(dynamicId) {
            if (!confirm('确定要删除这条动态吗？')) return;
            
            const response = await fetch('dt.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ action: 'delete_dynamic', id: dynamicId })
            });
            
            const result = await response.json();
            if (result.status === 'success') {
                // 从界面中删除动态
                const dynamicCard = document.querySelector(`[data-id="${dynamicId}"]`);
                if (dynamicCard) {
                    dynamicCard.remove();
                }
            } else {
                alert(result.message);
            }
        }
        
        // 发布动态
        async function postDynamic(event) {
            event.preventDefault();
            const title = document.querySelector('#title').value.trim();
            const content = document.querySelector('#content').value.trim();
            const allowComment = document.querySelector('#allow_comment').checked;
            const allowLike = document.querySelector('#allow_like').checked;
            
            const formData = new FormData();
            formData.append('action', 'post_dynamic');
            formData.append('title', title);
            formData.append('content', content);
            formData.append('allow_comment', allowComment ? 'on' : 'off');
            formData.append('allow_like', allowLike ? 'on' : 'off');
            
            const response = await fetch('dt.php', {
                method: 'POST',
                body: formData
            });
            
            const result = await response.json();
            if (result.status === 'success') {
                location.reload();
            } else {
                alert(result.message);
            }
        }
        
        // 查看用户资料
        function viewUser(username) {
            window.location.href = `userinfo.php?user=${encodeURIComponent(username)}`;
        }
    </script>
</body>
</html>